package com.scunewscreeper.service.schedule.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.kevinsawicki.http.HttpRequest;
import com.scunewscreeper.config.RedisConfig;
import com.scunewscreeper.config.WxConfig;
import com.scunewscreeper.repository.DataTNewsRepository;
import com.scunewscreeper.service.schedule.ScheduleService;
import com.scunewscreeper.service.websocket.WebSocketService;
import com.scunewscreeper.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * \* Date: 2021/11/17
 * \* Time: 20:58
 * \* Description: 定时任务实现类
 * \
 */
@Slf4j
@Service
@Component
@EnableScheduling
@EnableAsync
public class ScheduleServiceImpl implements ScheduleService {
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Value("${wx.grantType}")
    private String grantType;
    @Value("${wxToken.url}")
    private String tokenUrl;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private DataTNewsRepository dataRepo;
    /**
     * @Description: 定时获取全局唯一accessToken,调用微信后台API时需携带此access_token，服务器运行前调用一次
     * @Param:
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     */
    @PostConstruct
    @Async
    @Scheduled(cron = "*/7200 * * * * ?")
    public void getUserAccessToken() {
        log.info("获取access_token");
        Map<String, Object> json = null;
        try {
            String accessTokenUrl=tokenUrl+"?"+"grant_type="+grantType+"&appid="+appId+"&secret="+appSecret;
            // 发送请求
            String response = HttpRequest.get(accessTokenUrl).body();
            System.out.println(response);
            ObjectMapper mapper = new ObjectMapper();
            json = mapper.readValue(response, Map.class);
            WxConfig.access_token=json.get("access_token").toString();
            log.info("获取access_token成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 更新新闻浏览量定时任务
     * @param
     * @return void
     */
    @Async
    @Scheduled(cron = "*/10 * * * * ?")
    @Override
    public void GetReadNum() {
        try {
            if(redisUtil.hasKey(RedisConfig.redisReadNumKey)) {
                String redisKey = RedisConfig.redisReadNumKey;
                Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(redisUtil.hmget(redisKey)));
                for (Map.Entry<String, Object> entry : pMap.entrySet()) {
                    dataRepo.UpdateReadNum(entry.getKey(), ( Integer) entry.getValue());
                    redisUtil.hdel(redisKey, entry.getKey());
                }
            }
        }catch (Exception e){
            log.info("浏览量更新失败");
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * 清理消息队列定时任务
     * @param
     * @return void
     */
    @Override
    @Async
    @Scheduled(cron = "*/20 * * * * ?")
    public void ClearMessageLine() {
//        try{
//            if(redisUtil.hasKey(RedisConfig.messageLineKey)) {
//                log.info("处理消息队列");
//                Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(redisUtil.hmget(RedisConfig.messageLineKey)));
//                for (Map.Entry<String, Object> entry : pMap.entrySet()) {
//                    // 如果用户在线了，就发送此条消息，并删除
//                    if (webSocketService.IsUserOnline(entry.getKey())) {
//                        Map<String,Object> message= JSONObject.parseObject(entry.getValue().toString());
//                        //解析发送事件
//                        String event=message.get("event").toString();
//                        Map<String,Object> body=JSONObject.parseObject(JSON.toJSONString(message.get("body")));
//                        webSocketService.sendMsg(body,entry.getKey(),event);
//                        redisUtil.hdel(RedisConfig.messageLineKey, entry.getKey());
//                    }
//                }
//            }
//        }
//        catch (Exception e){
//            e.printStackTrace();
//            throw e;
        }
}

